package json

import (
	"encoding/json"
	"fmt"
	"os"
)

func main_4() {
	marshal_test()
	unmarsha1_test()
	unmarsha1_2map_test()
}

// 将 json  转成 map
func unmarsha1_2map_test() {
	var jsonBlob = []byte(`{
		"Name": "Platypus", 
		"Order": "Monotremata", 
		"child": {
			"Name": "Quoll",
			"Order": "Dasyuromorphia"
		}
	}`)

	// 将json 转 map
	var f map[string]interface{}
	json.Unmarshal(jsonBlob, &f)

	fmt.Printf("f: %v\n", f)

	for k, v := range f {
		fmt.Printf("k: %v\t v: %v\n", k, v)
	}

}

// json 转 对象
func unmarsha1_test() {
	var jsonBlob = []byte(`[
		{"Name": "Platypus", "Order": "Monotremata"},
		{"Name": "Quoll",    "Order": "Dasyuromorphia"}
	]`)

	type Animal struct {
		Name  string
		Order string
	}
	var animals []Animal
	err := json.Unmarshal(jsonBlob, &animals)
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Printf("%+v", animals)
	fmt.Println()
}

// 对象转成 json
func marshal_test() {
	type ColorGroup struct {
		ID     int
		Name   string
		Colors []string
	}
	group := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
	}
	b, err := json.Marshal(group)
	if err != nil {
		fmt.Println("error:", err)
	}

	// 写到控制台
	os.Stdout.Write(b)
	fmt.Println()
}
